@page
@model ListModel
@using Microsoft.AspNetCore.Mvc.RazorPages
@using OrchardCore.DisplayManagement;
@using OrchardCore.ContentManagement;
@using OrchardCore.ContentManagement.Display;
@using OrchardCore.DisplayManagement.ModelBinding;
@using OrchardCore.ContentManagement.Records;
@using YesSql;

@functions
{
    public class ListModel : PageModel
    {
        private readonly IContentManager _contentManager;
        private readonly IContentItemDisplayManager _contentDisplay;
        private readonly IUpdateModelAccessor _updateModelAccessor;
        private readonly ISession _session;

        public string Title { get; private set; }
        public List<dynamic> Items { get; private set; }

        [BindProperty]
        public string Text { get; set; }

        public ListModel(
            IContentManager contentManager,
            IContentItemDisplayManager contentDisplay,
            IUpdateModelAccessor updateModelAccessor,
            ISession session)
        {
            _contentManager = contentManager;
            _contentDisplay = contentDisplay;
            _updateModelAccessor = updateModelAccessor;
            _session = session;
        }

        public async Task OnGetAsync(string contentItemId)
        {
            var query = _session.Query<ContentItem, ContentItemIndex>()
                .With<ContentItemIndex>(x => x.ContentType == "Foo" && x.Published);
            var contentItems = await query.ListAsync();
            var updater = _updateModelAccessor.ModelUpdater;

            Items = new List<dynamic>();
            Title = "Foo List";

            foreach (var contentItem in contentItems)
            {
                Items.Add(await _contentDisplay.BuildDisplayAsync(contentItem, updater));
            }
        }

        public async Task<IActionResult> OnPostAsync()
        {
            var contentItem = await _contentManager.NewAsync("Foo");

            // Dynamic syntax
            contentItem.Content.TestContentPartA.Line = Text;
            await _contentManager.CreateAsync(contentItem);

            return RedirectToPage();
        }
    }
}

@await Html.PartialAsync("Header", Model)
<h2>Hello from @ViewContext.RouteData.Values["page"]</h2>

<ul class="list-group">
    <li class="list-group-item">
        <form asp-page="/Foo/List" method="post">
            <input asp-for="Text" />
            <button class="btn btn-sm btn-primary" type="submit">Add</button>
        </form>
    </li>
    @foreach (dynamic item in Model.Items)
    {
        <li class="list-group-item">
            @item.ContentItem.Content.TestContentPartA.Line
            <a asp-page="/Foo/Admin/Edit" asp-route-id="@item.ContentItem.ContentItemId"
               class="btn btn-warning btn-sm float-right">Manage</a>
        </li>
    }
</ul>
